<script>
import request from "../../../utils/request"
import hearing from "./components/hearing/hearing.vue"
import workingFillBlank from "./components/reading/workingFillBlank/index.vue"
import speedReading from "./components/reading/speedReading/index.vue"
import readingComprehension from "./components/reading/readingComprehension/index.vue"
import CET_translate from "./components/writing/CET_translate.vue"
import writing from "./components/writing/writing.vue"
import { getShowImage, handleUrlParams, isVip, showModal, valIsEmpty } from "@/utils"
import timer from "./components/timer.vue"
import AnalysisVideo from "./components/analysisVideo.vue"
import store from "../../../store"
import { practiceActionType } from "@/store/modules/practice"
import gestaltFillBlank from "./components/reading/gestaltFillBlank/index.vue"
import multipleCorresponding from "./components/reading/multipleCorresponding/index.vue"
import paragraphCorresponding from "./components/reading/paragraphCorresponding/index.vue"
import paragraphsSort from "@/practice/pages/index/components/reading/paragraphsSort/index.vue"
import KYTranslate from "@/practice/pages/index/components/reading/KYTranslate/index.vue"
import checkIsVip from "@/components/checkIsVip/index.vue"
import persistence from "@/store/persistence"
import websocket from "@/utils/websocket"
import vocabularyDetail from "@/components/vocabularyDetail.vue"
import studyRoomFloat from "@/components/studyRoomFloat/index.vue"
import practiceReport from "@/practice/pages/index/components/practiceReport.vue"

export default {
  name: "index",
  components: {
    AnalysisVideo,
    hearing,
    workingFillBlank,
    speedReading,
    readingComprehension,
    CET_translate,
    writing,
    timer,
    gestaltFillBlank,
    multipleCorresponding,
    paragraphCorresponding,
    paragraphsSort,
    KYTranslate,
    checkIsVip,
    vocabularyDetail,
    studyRoomFloat,
    practiceReport,
  },
  data() {
    return {
      queryParams: {
        structureId: "",
        typeCode: "",
      },
      currentTab: "practice",
      isVip: false,
      details: null,
      //全局css变量
      globalCssVariables: {
        fontSizeRate: persistence.practiceSettings.getItem("fontSizeRate") || 1, //字体大小倍率
      },
    }
  },
  async onShow() {
    this.isVip = await isVip()
    websocket.trackCurrentPage("刷题界面", "BRUSH_QUESTIONS", 1).catch(() => {})
  },
  computed: {
    //是否显示答案解析（供其余的嵌套组件共享）
    viewAnalysis: {
      get() {
        store.commit(practiceActionType.mutations.setViewAnalysis, this.currentTab === "analysis")
        return store.getters[practiceActionType.getters.getViewAnalysis]
      },
      set(boolean) {
        store.commit(practiceActionType.mutations.setViewAnalysis, boolean)
        if (boolean) {
          this.currentTab = "analysis"
        }
      },
    },
  },
  async onLoad(query) {
    this.queryParams = query
    if (query.currentTab) {
      this.currentTab = query.currentTab
    }
    //之前做过了直接显示解析
    if (query.doTopicUser && query.doTopicUser !== "0") {
      this.viewAnalysis = true
      this.getRecord()
    } else {
      this.getStructureDetails()
      wx.enableAlertBeforeUnload({
        message: "你有未提交的答题数据，确定要离开吗？",
        confirmButtonText: "继续答题",
        cancelButtonText: "确定离开",
      })
    }
  },
  //页面被销毁之前停止计时器
  beforeDestroy() {
    websocket.trackCurrentPage("刷题界面", "BRUSH_QUESTIONS", 2).catch(() => {})
  },
  methods: {
    showModal,
    valIsEmpty,
    getShowImage,
    //获取题目结构详情
    getStructureDetails() {
      request({
        url: "topic/getDetails",
        data: this.queryParams,
        errorHandle: true,
        showLoading: true,
      }).then((data) => {
        //处理题干里面的富文本的图片溢出的问题
        data.topicStem = data.topicStem.replace(/(<img[^>]*)(style="")/g, '$1style="max-width:100%;height:auto"')
        this.setTitle(data)
        this.setDetailsForChildComponent(data)
      })
    },
    //获取做题记录
    getRecord() {
      request({
        url: "userDoTopic/getDoTopicDetails",
        data: this.queryParams,
        errorHandle: true,
        showLoading: true,
      }).then((data) => {
        this.setTitle(data)
        this.setDetailsForChildComponent(data)
      })
    },
    //获取详情
    getDetails() {
      if (this.viewAnalysis) {
        this.getRecord()
      } else {
        this.getStructureDetails()
      }
    },
    // 将详情设置给子组件
    setDetailsForChildComponent(data) {
      // 考研题型
      if (this.queryParams.typeCode === "KY_TRANSLATE") {
				this.details = data
        this.$nextTick(() => {
          this.$refs.KYTranslate.setDetails(data)
        })
        // 通用组件
      } else {
        //触发数据刷新
        this.details = null
        console.log(data, "this.details")
        this.$nextTick(() => {
          this.details = data
        })
      }
    },
    //根据题目结构名称动态设置页面标题
    setTitle(detail) {
      if (detail.structureYear && detail.structureName) {
        uni.setNavigationBarTitle({
          title: detail.structureYear + " " + detail.structureName,
        })
      }
    },
    //提交做题记录
    async submitRecord(params = {}) {
      const submitData = {
        topicId: this.details.topicId,
        structureId: this.details.structureId,
        typeCode: this.queryParams.typeCode,
        ...params,
      }
      //获取计时器秒数
      if (!submitData.userDoTopicScore) submitData.userDoTopicScore = {}
      submitData.userDoTopicScore.useTime = this.$refs.timer.time
      await request({
        url: "userDoTopic/add",
        data: submitData,
        showLoading: true,
        errorHandle: true,
      })
      //弹出做题报告
      if (submitData && submitData.userDoTopicScore && submitData.userDoTopicScore.isCalculateScore === 1) {
        await this.$refs.practiceReport.open(submitData.userDoTopicScore)
      }
      //切换到查看解析
      this.viewAnalysis = true
    },
    //显示开通会员提示框
    showVipTips() {
      this.$refs.checkIsVip.checkIsVip()
    },
    checkIsVip() {
      if (this.isVip) {
        return true
      }
      this.$refs.checkIsVip.checkIsVip()
      return false
    },
    //重点词汇查看详情弹框
    vocabularyDetailPopupOpen(wordName) {
      this.$refs.vocabularyDetail.open(wordName)
    },
  },
  watch: {
    viewAnalysis: {
      handler(val) {
        //查看解析拿做题记录
        if (val) {
          wx.disableAlertBeforeUnload()
          //做题模式
        } else {
          //监听页面返回，提示用户是否需要提交做题记录
          wx.enableAlertBeforeUnload({
            message: "你有未提交的答题数据，确定要离开吗？",
            confirmButtonText: "继续答题",
            cancelButtonText: "确定离开",
          })
        }
        this.getDetails()
      },
    },
  },
  provide() {
    return {
      root: this,
    }
  },
}
</script>

<template>
  <view class="page" :style="{ '--font-size-rate': globalCssVariables.fontSizeRate }">
    <view class="tag-list">
      <view class="tag-item" :class="{ active: currentTab === 'practice' }" @click="currentTab = 'practice'">练习 </view>
      <view
        class="tag-item"
        :class="{ active: currentTab === 'analysis' }"
        @click="
          () => {
            if (currentTab === 'practice') {
              showModal({
                title: '提示',
                content: '您有未提交的答题数据，确定要继续吗？',
              }).then((confirm) => {
                confirm && (currentTab = 'analysis')
              })
            } else {
              currentTab = 'analysis'
            }
          }
        "
        >答案
      </view>
      <view
        v-if="details.videoFileUrl"
        class="tag-item"
        :class="{ active: currentTab === 'videoAnalysis' }"
        @click="currentTab = 'videoAnalysis'"
        >视频讲解
      </view>
    </view>
    <!--		解题模式下的计时器-->
    <view class="timer-container" v-if="currentTab === 'practice'">
      <timer ref="timer"></timer>
    </view>
    <template v-if="details">
      <!--		视频讲解-->
      <view style="margin-top: 20rpx" v-if="currentTab === 'videoAnalysis'">
        <analysis-video :videoFileUrl="details.videoFileUrl"></analysis-video>
      </view>
      <template v-else>
        <!--		听力题-->
        <hearing v-if="queryParams.typeCode === 'HEARING'" :viewAnalysis.sync="viewAnalysis" @submit="submitRecord" :details="details">
          <!--		题干-->
          <view class="topic-paragraph-item" v-if="!valIsEmpty(details.topicStem)">
            <view v-html="details.topicStem"></view>
          </view>
        </hearing>
        <!--		选词填空-->
        <workingFillBlank
          v-else-if="queryParams.typeCode === 'WORDING_FILL_BLANK'"
          :view-analysis.sync="viewAnalysis"
          @submit="submitRecord"
          :details="details"
        >
          <!--		题干-->
          <view class="topic-paragraph-item" v-if="!valIsEmpty(details.topicStem)">
            <view v-html="details.topicStem"></view>
          </view>
        </workingFillBlank>
        <!--		快速阅读-->
        <speedReading
          v-else-if="queryParams.typeCode === 'SPEED_READING'"
          :view-analysis.sync="viewAnalysis"
          @submit="submitRecord"
          :details="details"
        >
          <!--		题干-->
          <view class="topic-paragraph-item" v-if="!valIsEmpty(details.topicStem)">
            <view v-html="details.topicStem"></view>
          </view>
        </speedReading>
        <!--		阅读理解-->
        <readingComprehension
          v-else-if="queryParams.typeCode === 'READING_COMPREHENSION'"
          :view-analysis.sync="viewAnalysis"
          @submit="submitRecord"
          :details="details"
        >
          <!--		题干-->
          <view class="topic-paragraph-item" v-if="!valIsEmpty(details.topicStem)">
            <view v-html="details.topicStem"></view>
          </view>
        </readingComprehension>
        <!--		四六级翻译-->
        <CET_translate
          v-else-if="queryParams.typeCode === 'CET_TRANSLATE'"
          :view-analysis.sync="viewAnalysis"
          @submit="submitRecord"
          :details="details"
        >
          <!--		题干-->
          <view class="topic-paragraph-item" v-if="!valIsEmpty(details.topicStem)">
            <view v-html="details.topicStem"></view>
          </view>
        </CET_translate>
        <!--		写作题-->
        <writing
          v-else-if="queryParams.typeCode === 'WRITING'"
          :view-analysis.sync="viewAnalysis"
          @submit="submitRecord"
          :details="details"
        >
          <!--		题干-->
          <view class="topic-paragraph-item" v-if="!valIsEmpty(details.topicStem)">
            <view v-html="details.topicStem"></view>
          </view>
        </writing>
        <!--				完形填空（考研）-->
        <gestaltFillBlank
          v-else-if="queryParams.typeCode === 'GESTALT_FILL_BLANK'"
          :view-analysis.sync="viewAnalysis"
          @submit="submitRecord"
          :details="details"
        >
          <!--		题干-->
          <view class="topic-paragraph-item" v-if="!valIsEmpty(details.topicStem)">
            <view v-html="details.topicStem"></view>
          </view>
        </gestaltFillBlank>
        <!--				多项对应-->
        <multipleCorresponding
          v-else-if="queryParams.typeCode === 'MULTIPLE_CORRESPONDING'"
          :view-analysis.sync="viewAnalysis"
          @submit="submitRecord"
        ></multipleCorresponding>
        <!--				段落对应-->
        <paragraphCorresponding
          v-else-if="queryParams.typeCode === 'PARAGRAPH_CORRESPONDING'"
          :view-analysis.sync="viewAnalysis"
          @submit="submitRecord"
        ></paragraphCorresponding>
        <!--				段落排序-->
        <paragraphsSort
          v-else-if="queryParams.typeCode === 'PARAGRAPHS_SORT'"
          :view-analysis.sync="viewAnalysis"
          @submit="submitRecord"
        ></paragraphsSort>
        <!--				考研翻译-->
        <KYTranslate
          ref="KYTranslate"
          v-else-if="queryParams.typeCode === 'KY_TRANSLATE'"
          :view-analysis.sync="viewAnalysis"
          @submit="submitRecord"
          @getDetails="getDetails"
        ></KYTranslate>
      </template>
    </template>

    <checkIsVip ref="checkIsVip"></checkIsVip>
    <vocabularyDetail ref="vocabularyDetail"></vocabularyDetail>
    <studyRoomFloat></studyRoomFloat>
    <!--		做题报告-->
    <practiceReport ref="practiceReport"></practiceReport>
  </view>
</template>

<style lang="scss">
rich-text {
  font-size: calc(32rpx * var(--font-size-rate));
  line-height: 2;
}
</style>

<style scoped lang="scss">
.page {
  .tag-list {
    display: flex;
    .tag-item {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: calc(36rpx * var(--font-size-rate));
      padding: 0 30rpx;
      width: 0;
      flex: 1;
      height: 80rpx;
      position: relative;
      &.active {
        font-weight: bold;
      }
      &.active::after {
        content: "";
        display: block;
        position: absolute;
        left: 50%;
        bottom: 6rpx;
        width: 20%;
        transform: translateX(-50%);
        height: 8rpx;
        border-radius: 4rpx;
        background: var(--theme-color);
      }
    }
  }
  .topic-paragraph-item {
    font-size: calc(32rpx * var(--font-size-rate));
    line-height: 2;
    padding: 20rpx 0;
  }
  .timer-container {
    //position: sticky;
    //top: 0;
    //left: 0;
    //right: 0;
    //z-index: 12;
  }
}
</style>
